from django.apps import AppConfig


class LoggingsConfig(AppConfig):
    name = 'loggings'
    verbose_name = '日志系统'

    def ready(self):
        """在应用启动时初始化日志系统"""
        import logging
        logger = logging.getLogger('system')
        
        # 记录系统启动信息
        try:
            logger.info("系统启动")
        except Exception as e:
            # 如果日志系统还没准备好，则不记录
            pass
        
        # 注册信号处理器
        try:
            self._register_signal_handlers()
        except Exception as e:
            # 如果信号系统出问题，不阻止应用启动
            pass
    
    def _register_signal_handlers(self):
        """注册Django信号处理器"""
        try:
            # 导入用户日志模块
            from django.contrib.auth.signals import user_logged_in, user_logged_out, user_login_failed
            
            # 在这里直接定义处理器函数，避免循环导入
            import logging
            user_logger = logging.getLogger('user')
            
            def handle_user_login(sender, request, user, **kwargs):
                if request and user:
                    ip = request.META.get('REMOTE_ADDR', 'unknown')
                    user_logger.info(f"用户登录: {user.username} (ID:{user.id}) 来自IP:{ip}")
            
            def handle_user_logout(sender, request, user, **kwargs):
                if user:
                    user_logger.info(f"用户登出: {user.username} (ID:{user.id})")
            
            def handle_login_failed(sender, credentials, request, **kwargs):
                username = credentials.get('username', '<unknown>')
                ip = request.META.get('REMOTE_ADDR', 'unknown') if request else 'N/A'
                user_logger.warning(f"登录失败: 用户名={username} 来自IP:{ip}")
            
            # 注册用户登录/登出信号处理器
            user_logged_in.connect(handle_user_login)
            user_logged_out.connect(handle_user_logout)
            user_login_failed.connect(handle_login_failed)
            
            user_logger.info("用户日志系统初始化成功")
            
        except Exception as e:
            # 简单记录错误但不阻止应用启动
            import logging
            logging.error(f"注册用户日志处理器失败: {e}")
            pass 